package com.gph.saviorframework.security.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gph.saviorframework.Constants;
import com.gph.saviorframework.FieldType;
import com.gph.saviorframework.common.model.User;
import com.gph.saviorframework.dao.security.UserDao;
import com.gph.saviorframework.security.service.UserService;
import com.gph.saviorframework.util.SecUtils;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    private Map<String, String> fields = new HashMap<String, String>();

    public UserServiceImpl(){
        fields.put("USER_ID", FieldType.STRING);
        fields.put("USER_NAME",FieldType.STRING);
        fields.put("ORG_ID",FieldType.STRING);
        fields.put("USER_EMAIL",FieldType.STRING);
        fields.put("USER_ENABLED",FieldType.STRING);
        fields.put("ROLE_ID",FieldType.STRING);
    }

    /**
     * 保存
     *
     * @param user
     */
    public void save(User user) {
        userDao.save(user);
    }

    /**
     * 根据编号获取
     *
     * @param id
     * @return
     */
    public User get(String id) {
        return userDao.get(id);
    }

    /**
     * 更新
     *
     * @param user
     * @return
     */
    public void update(User user) {
        userDao.update(user);
    }

    /**
     * 批量更新
     *
     * @param users
     */
    @Override
    public void update(Set<User> users) {
        for(User user : users){
            update(user);
        }
    }

    /**
     * 根据条件返回数据
     *
     * @param sort
     * @param dir
     * @param params
     * @return
     */
    public List<Map<String, Object>> find(String sort, String dir, Map<String, Object> params) {
        return find(StringUtils.EMPTY, sort, dir, params);
    }

    /**
     * 带分页参数的，给bootstrap使用的
     *
     * @param start  开始页码，从1开始
     * @param limit  每页查询的次数
     * @param sort
     * @param dir
     * @param params
     * @return
     */
    @Override
    public Map<String, Object> find(int start, int limit, String sort, String dir, Map<String, Object> params,Object... extras) {
        Map<String,Object> map = new HashMap<String, Object>();

        if(extras.length==1){
            String org = extras[0].toString();
            PageHelper.startPage(start, limit);
            List<Map<String,Object>> list = find(org,sort, dir, params);
            PageInfo pageInfo = new PageInfo(list);

            map.put(Constants.DEFAULT_RECORD_MODEL_KEY, list);
            map.put(Constants.DEFAULT_COUNT_MODEL_KEY, pageInfo.getPages());
            map.put(Constants.DEFAULT_RECORDS_MODEL_KEY,pageInfo.getTotal());
            map.put(Constants.DEFAULT_SUCCESS_KEY, Boolean.TRUE);
        }

        return map;
    }

    /**
     * 统计数量
     *
     * @param params
     * @return
     */
    public long count(Map<String, Object> params) {
        return count(StringUtils.EMPTY,params);
    }

    /**
     * 根据主键删除
     *
     * @param id
     */
    public void delete(String id) {
        userDao.deleteById(id);
    }

    /**
     * 批量删除
     *
     * @param ids
     */
    public void deleteByIds(String[] ids) {
        for(String id : ids){
            delete(id);
        }
    }

    /**
     * 查询字段集合
     *
     * @return
     */
    public Map<String, String> getFields() {
        return fields;
    }

    /**
     * 根据id查询map
     *
     * @param id
     * @return
     */
    public Map<String, Object> findById(String id) {
        return userDao.findByUsername(id);
    }

    /**
     * 生成where条件
     *
     * @param params
     * @param extra
     * @return
     */
    public String genWhereClause(Map<String, Object> params, Object... extra) {
        String whereClause = "1=1";
        if(extra.length==1){
            String org = extra[0].toString();
            if(!StringUtils.isEmpty(org)){
                whereClause+=" AND U.ORG_ID='"+org+"'";
            }
        }
        if (params!=null && params.keySet().size() > 0) {
            for (String key : params.keySet()) {
                if("ROLE_ID".equals(key))
                    whereClause += " AND R." + key + " LIKE '"+params.get(key)+"'";
                else if (fields.get(key).equals(FieldType.STRING)) {
                    whereClause += " AND U." + key + " LIKE '"+params.get(key)+"'";
                } else {
                    whereClause += " AND U." + key + " ='"+params.get(key)+"'";
                }
            }
        }
        return whereClause;
    }

    /**
     * 重置位初始密码
     *
     * @param username
     */
    public void resetPassword(String username) {
        userDao.resetPassword(username, SecUtils.getMD5(Constants.DEFAULT_PASSWORD.getBytes()));
    }

    @Override
    public void resetPassword(String username, String newPwd) {
        userDao.resetPassword(username,SecUtils.getMD5(newPwd.getBytes()));
    }

    /**
     * 根据组织编号等条件查询用户信息
     *
     * @param org
     * @param sort
     * @param dir
     * @param params
     * @return
     */
    public List<Map<String, Object>> find(String org, String sort, String dir, Map<String, Object> params) {
        return userDao.find(sort,dir,genWhereClause(params,org));
    }

    @Override
    public Map<String, Object> findFuzzy(int start, int limit, String sort, String dir, Map<String, Object> params, Object... extras) {
        Map<String,Object> map = new HashMap<String, Object>();

        if(extras.length==1){
            String org = extras[0].toString();
            PageHelper.startPage(start, limit);
            List<Map<String,Object>> list = findFuzzy(org, sort, dir, params);
            PageInfo pageInfo = new PageInfo(list);

            map.put(Constants.DEFAULT_RECORD_MODEL_KEY, list);
            map.put(Constants.DEFAULT_COUNT_MODEL_KEY, pageInfo.getPages());
            map.put(Constants.DEFAULT_RECORDS_MODEL_KEY,pageInfo.getTotal());
            map.put(Constants.DEFAULT_SUCCESS_KEY, Boolean.TRUE);
        }
        return map;
    }

    private List<Map<String, Object>> findFuzzy(String org, String sort, String dir, Map<String, Object> params) {
        return userDao.find(sort,dir,genWhereClauseFuzzy(params,org));
    }

    /**
     * 生成where条件
     *
     * @param params
     * @param extra
     * @return
     */
    private String genWhereClauseFuzzy(Map<String, Object> params, Object... extra) {
        String whereClause = "1=1";
        if(extra.length==1){
            String org = extra[0].toString();
            if(!StringUtils.isEmpty(org)){
                whereClause+=" AND U.ORG_ID='"+org+"'";
            }
        }
        if (params!=null && params.keySet().size() > 0) {
            //拼接类似(t.USER_NAME='guopeihui' or t.USER_ID='guopeihui')的sql
            whereClause += " AND (";
            int i=0;
            for (String key : params.keySet()) {
                if (fields.get(key).equals(FieldType.STRING)) {
                    if(i==0){

                        whereClause += "U." + key + " LIKE '"+params.get(key)+"'";
                    }
                    else{
                        whereClause += " OR U." + key + " LIKE '"+params.get(key)+"'";
                    }
                }
                else {
                    if(i==0){
                        whereClause += "U." + key + " ='"+params.get(key)+"'";
                    }
                    else{
                        whereClause += " OR U." + key + " ='"+params.get(key)+"'";
                    }
                }
                i++;
            }
            whereClause += ")";
        }
        return whereClause;
    }

    @Transactional(readOnly = true)
    @Override
    public List<User> findByOrgId(String orgId) {
        return userDao.getUsersByOrgId(orgId);
    }

    /**
     * 根据组织编号获取用户编号集合
     *
     * @param orgId
     * @return
     */
    @Override
    public List<String> getUserIdsByOrgId(String orgId) {
        return userDao.getUserIdsByOrgId(orgId);
    }

    /**
     * 获取所有的用户编号集合
     *
     * @return
     */
    @Override
    public List<String> getIds() {
        return userDao.getIds();
    }

    /**
     * 查询记录数
     *
     * @param org
     * @param params
     * @return
     */
    public long count(String org, Map<String, Object> params) {
        return userDao.count(genWhereClause(params,org));
    }

    /**
     * 清除关联的角色
     *
     * @param username
     */
    public void clearRole(String username) {
        userDao.clearRole(username);
    }

    /**
     * 保存用户和角色之间的关系
     *
     * @param roleIds
     * @param username
     */
    public void saveUserRole(String[] roleIds, String username) {
        clearRole(username);
        if(roleIds!=null) {
            for (String id : roleIds) {
                userDao.saveUserRole(username, id);
            }
        }
    }

    /**
     * 通过org和role查询
     *
     * @param org
     * @param role
     * @return
     */
    public List<Map<String, Object>> findByOrgAndRole(String org, String role) {
        return userDao.findByOrgAndRole(org,role);
    }

    /**
     * 是否存在用户
     *
     * @param userName
     * @return
     */
    @Override
    public boolean existUser(String userName) {
        if(userDao.count("1=1 AND U.USER_ID='"+userName+"'")>0){
            return true;
        }
        return false;
    }

    /**
     * 判断是否存在email
     *
     * @param email
     * @return
     */
    @Override
    public boolean existEmail(String email) {
        if(userDao.count("1=1 AND U.USER_EMAIL='"+email+"'")>0){
            return true;
        }
        return false;
    }

    /**
     * 分配分管人员
     *
     * @param userId
     * @param userIds
     */
    @Override
    public void assignUsers(String userId, String[] userIds) {

    }

    /**
     * 分配分管部门
     *
     * @param userId
     * @param orgIds
     */
    @Override
    public void assigenOrgs(String userId, String[] orgIds) {

    }

    /**
     * 批量保存
     *
     * @param users
     */
    @Transactional
    @Override
    public void batchSave(List<User> users) {
        userDao.batchSave(users);
    }

    /**
     * 和数据权限相关的
     *
     * @param userIds***
     */
    @Override
    public List<Map<String, Object>> findByPermission(List<String> userIds,Map<String, Object> params) {
        return userDao.findByPermission(userIds,genWhereClause(params));
    }

    @Override
    public Map<String, Object> findByPermission1(int start, int limit, List<String> userIds, Map<String, Object> params) {
        Map<String,Object> map = new HashMap<String, Object>();

        PageHelper.startPage(start, limit);
        List<Map<String,Object>> list = findByPermission(userIds, params);
        PageInfo pageInfo = new PageInfo(list);

        map.put(Constants.DEFAULT_RECORD_MODEL_KEY, list);
        map.put(Constants.DEFAULT_COUNT_MODEL_KEY, pageInfo.getPages());
        map.put(Constants.DEFAULT_RECORDS_MODEL_KEY,pageInfo.getTotal());
        map.put(Constants.DEFAULT_SUCCESS_KEY, Boolean.TRUE);

        return map;
    }

    @Override
    public Map<String, String> getIdNames(){
        List<Map<String, String>> list = userDao.getIdNames();
        Map<String, String> reMap = new HashMap<String, String>();
        for (Map<String, String> map : list) {
            reMap.put(map.get("username").toString(), map.get("name").toString());
        }
        return reMap;
    }

    @Override
    public User findByCertificateNum(String certificateNum) {
        return userDao.findByCertificateNum(certificateNum);
    }

    @Override
	public List<Map<String, Object>> findByRoles(List<String> roleIds) {
		return userDao.findByRoles(roleIds);
	}

	@Override
	public Map<String, Object> findByRoles(int start, int limit,
			List<String> roleIds) {
		Map<String,Object> map = new HashMap<String, Object>();

        PageHelper.startPage(start, limit);
        List<Map<String,Object>> list = findByRoles(roleIds);
        PageInfo pageInfo = new PageInfo(list);

        map.put(Constants.DEFAULT_RECORD_MODEL_KEY, list);
        map.put(Constants.DEFAULT_COUNT_MODEL_KEY, pageInfo.getPages());
        map.put(Constants.DEFAULT_RECORDS_MODEL_KEY,pageInfo.getTotal());
        map.put(Constants.DEFAULT_SUCCESS_KEY, Boolean.TRUE);

        return map;
	}
}
